using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

using Barbar.MapReport.Configuration;
using System.Collections.Specialized;
using Barbar.MapReport.DataSource.Resources;
using System.Configuration;
using Barbar.MapReport.DataSource.Entities;

namespace Barbar.MapReport.DataSource {
  public class RegionProviderDB : RegionProvider {
    private string m_ConnectionStringName;

    public override void Initialize(string name, NameValueCollection config) {
      base.Initialize(name, config);

      if (config == null)
        throw new ArgumentNullException("config");

      m_ConnectionStringName = config["connectionStringName"];
      if (String.IsNullOrEmpty(m_ConnectionStringName))
        throw new DataSourceException(Translator.Error_ConnectionStringNameNotSpecified);
    }

    public override IEnumerable<IRawRegion> Regions {
      get {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[m_ConnectionStringName].ConnectionString)) {
          SqlCommand cmd = new SqlCommand("GetRegions", conn);
          cmd.CommandType = CommandType.StoredProcedure;
          conn.Open();
          using (SqlDataReader reader = cmd.ExecuteReader()) {
            while (reader.Read()) {
              RawRegion rawRegion = new RawRegion();
              rawRegion.Id = reader.GetString(reader.GetOrdinal("id_Region"));
              rawRegion.Name = reader.GetString(reader.GetOrdinal("Name"));
              if (!reader.IsDBNull(reader.GetOrdinal("id_Parent")))
                rawRegion.ParentId = reader.GetString(reader.GetOrdinal("id_Parent"));
              yield return rawRegion;
            }
          }
        }
      }
    }
  }
}
